import logging
import os
from functools import wraps


class SingletonLogger:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(SingletonLogger, cls).__new__(cls)
        return cls._instance

    def __init__(self, name='app', log_level=logging.INFO, log_file='app.log'):
        if not hasattr(self, 'initialized'):
            self.logger = logging.getLogger(name)
            self.logger.setLevel(log_level)

            if not self.logger.handlers:
                # 创建formatter
                formatter = logging.Formatter(
                    '%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
                )

                # 控制台handler
                console_handler = logging.StreamHandler()
                console_handler.setLevel(log_level)
                console_handler.setFormatter(formatter)
                self.logger.addHandler(console_handler)

                # 文件handler
                if log_file:
                    log_dir = os.path.dirname(log_file)
                    if log_dir and not os.path.exists(log_dir):
                        os.makedirs(log_dir)

                    file_handler = logging.FileHandler(log_file, encoding='utf-8')
                    file_handler.setLevel(log_level)
                    file_handler.setFormatter(formatter)
                    self.logger.addHandler(file_handler)

            self.initialized = True

    def get_logger(self):
        return self.logger


# 创建全局logger
_logger_instance = SingletonLogger().get_logger()


# 提供便捷的日志方法
def debug(msg):
    _logger_instance.debug(msg)


def info(msg):
    _logger_instance.info(msg)


def warning(msg):
    _logger_instance.warning(msg)


def error(msg):
    _logger_instance.error(msg)


def critical(msg):
    _logger_instance.critical(msg)